<template>
  <div class="family-photos-container">
    <div class="header">
      <h2>老人照片</h2>
      <p>查看护工为您家老人上传的活动照片</p>
    </div>

    <div class="filter-section">
      <el-card>
        <div class="filter-content">
          <div class="filter-item">
            <span class="filter-label">老人：</span>
            <el-select v-model="filterForm.elderId" placeholder="请选择老人" @change="handleFilterChange">
              <el-option label="全部老人" value=""></el-option>
              <el-option
                v-for="elder in elderList"
                :key="elder.elderId"
                :label="elder.name"
                :value="elder.elderId"
              />
            </el-select>
          </div>
          
          <div class="filter-item">
            <span class="filter-label">时间范围：</span>
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleFilterChange"
            />
          </div>

          <div class="filter-item">
            <el-button type="primary" @click="loadPhotoList">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <div class="photo-list-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>照片列表</span>
            <div class="header-actions">
              <el-button type="primary" text @click="loadPhotoList">刷新</el-button>
              <el-button type="success" text @click="handleDownloadAll">
                下载全部
              </el-button>
            </div>
          </div>
        </template>

        <div class="photo-grid" v-loading="loading">
          <div class="photo-item" v-for="photo in photoList" :key="photo.photoId">
            <div class="photo-card">
              <div class="photo-image-container">
                <el-image
                  :src="photo.photoUrl"
                  :preview-src-list="previewList"
                  fit="cover"
                  class="photo-image"
                  @click="handlePreview(photo)"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                      <span>图片加载失败</span>
                    </div>
                  </template>
                </el-image>
                <div class="photo-overlay">
                  <el-button type="primary" text @click="handleDownload(photo)">
                    <el-icon><Download /></el-icon>
                    下载
                  </el-button>
                </div>
              </div>
              
              <div class="photo-info">
                <div class="elder-info">
                  <el-tag type="primary" size="small">{{ getElderName(photo.elderId) }}</el-tag>
                </div>
                <div class="photo-desc">{{ photo.description }}</div>
                <div class="photo-meta">
                  <div class="uploader">
                    <el-icon><User /></el-icon>
                    <span>护工上传</span>
                  </div>
                  <div class="upload-time">
                    <el-icon><Clock /></el-icon>
                    <span>{{ formatTime(photo.createTime) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="empty-state" v-if="photoList.length === 0 && !loading">
            <el-empty description="暂无照片" />
          </div>
        </div>

        <div class="pagination" v-if="photoList.length > 0">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[12, 24, 48, 96]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 照片预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="照片预览"
      width="60%"
      :before-close="handlePreviewClose"
    >
      <div class="preview-content">
        <el-image
          :src="currentPreviewPhoto?.photoUrl"
          fit="contain"
          style="width: 100%; max-height: 500px;"
        >
          <template #error>
            <div class="preview-error">
              <el-icon><Picture /></el-icon>
              <span>图片加载失败</span>
            </div>
          </template>
        </el-image>
        
        <div class="preview-info" v-if="currentPreviewPhoto">
          <h3>照片信息</h3>
          <div class="info-item">
            <span class="label">老人：</span>
            <span>{{ getElderName(currentPreviewPhoto.elderId) }}</span>
          </div>
          <div class="info-item">
            <span class="label">描述：</span>
            <span>{{ currentPreviewPhoto.description }}</span>
          </div>
          <div class="info-item">
            <span class="label">上传时间：</span>
            <span>{{ formatTime(currentPreviewPhoto.createTime) }}</span>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="handlePreviewClose">关闭</el-button>
        <el-button type="primary" @click="handleDownload(currentPreviewPhoto)">
          下载照片
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture, Download, User, Clock } from '@element-plus/icons-vue'
import { elderApi } from '@/api/elder'
import { getFamilyPhotos } from '@/api/photo'

// 响应式数据
const loading = ref(false)
const previewDialogVisible = ref(false)
const currentPreviewPhoto = ref(null)

const filterForm = reactive({
  elderId: '',
  dateRange: []
})

const elderList = ref([])
const photoList = ref([])

const pagination = reactive({
  currentPage: 1,
  pageSize: 12,
  total: 0
})

// 计算属性
const previewList = computed(() => {
  return photoList.value.map(photo => photo.photoUrl)
})

// 方法
const loadElderList = async () => {
  try {
    const response = await elderApi.getElders()
    if (response.data && response.data.success) {
      elderList.value = response.data.data || []
    }
  } catch (error) {
    ElMessage.error('获取老人列表失败')
    console.error('获取老人列表失败:', error)
  }
}

const loadPhotoList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      elderId: filterForm.elderId || undefined
    }

    // 添加时间范围过滤
    if (filterForm.dateRange && filterForm.dateRange.length === 2) {
      params.startDate = filterForm.dateRange[0]
      params.endDate = filterForm.dateRange[1]
    }

    const response = await getFamilyPhotos(params)
    if (response.data && response.data.success) {
      photoList.value = response.data.data?.records || []
      pagination.total = response.data.data?.total || 0
    }
  } catch (error) {
    ElMessage.error('获取照片列表失败')
    console.error('获取照片列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleFilterChange = () => {
  pagination.currentPage = 1
  loadPhotoList()
}

const resetFilter = () => {
  filterForm.elderId = ''
  filterForm.dateRange = []
  pagination.currentPage = 1
  loadPhotoList()
}

const handlePreview = (photo) => {
  currentPreviewPhoto.value = photo
  previewDialogVisible.value = true
}

const handlePreviewClose = () => {
  previewDialogVisible.value = false
  currentPreviewPhoto.value = null
}

const handleDownload = async (photo) => {
  if (!photo || !photo.photoUrl) {
    ElMessage.warning('无法下载该照片')
    return
  }

  try {
    // 创建下载链接
    const link = document.createElement('a')
    link.href = photo.photoUrl
    link.download = `老人照片_${getElderName(photo.elderId)}_${formatTime(photo.createTime, 'YYYYMMDDHHmmss')}.jpg`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('开始下载照片')
  } catch (error) {
    ElMessage.error('下载照片失败')
    console.error('下载照片失败:', error)
  }
}

const handleDownloadAll = () => {
  if (photoList.value.length === 0) {
    ElMessage.warning('没有可下载的照片')
    return
  }

  ElMessage.info('批量下载功能开发中，请逐一下载')
}

const getElderName = (elderId) => {
  const elder = elderList.value.find(item => item.elderId === elderId)
  return elder ? elder.name : '未知老人'
}

const formatTime = (time, format = 'default') => {
  if (!time) return ''
  
  const date = new Date(time)
  
  if (format === 'YYYYMMDDHHmmss') {
    return date.toISOString().replace(/[-:]/g, '').replace(/\..+/, '').slice(0, 14)
  }
  
  return date.toLocaleString('zh-CN')
}

const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize
  pagination.currentPage = 1
  loadPhotoList()
}

const handleCurrentChange = (newPage) => {
  pagination.currentPage = newPage
  loadPhotoList()
}

// 生命周期
onMounted(() => {
  loadElderList()
  loadPhotoList()
})
</script>

<style scoped>
.family-photos-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.header p {
  margin: 5px 0 0 0;
  color: #909399;
  font-size: 14px;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-content {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-label {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.photo-list-section {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.photo-item {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
}

.photo-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.photo-card {
  background: white;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.photo-image-container {
  position: relative;
  overflow: hidden;
}

.photo-image {
  width: 100%;
  height: 200px;
  display: block;
  cursor: pointer;
  transition: transform 0.3s;
}

.photo-image:hover {
  transform: scale(1.05);
}

.photo-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.photo-image-container:hover .photo-overlay {
  opacity: 1;
}

.image-slot {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  gap: 8px;
}

.photo-info {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.elder-info {
  margin-bottom: 8px;
}

.photo-desc {
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
  flex: 1;
}

.photo-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.uploader, .upload-time {
  display: flex;
  align-items: center;
  gap: 4px;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 40px 0;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.preview-content {
  text-align: center;
}

.preview-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
  color: #909399;
  gap: 8px;
}

.preview-info {
  margin-top: 20px;
  text-align: left;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 4px;
}

.preview-info h3 {
  margin: 0 0 12px 0;
  color: #303133;
}

.info-item {
  display: flex;
  margin-bottom: 8px;
}

.info-item .label {
  color: #606266;
  min-width: 80px;
}

@media (max-width: 768px) {
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-item {
    justify-content: space-between;
  }
  
  .photo-grid {
    grid-template-columns: 1fr;
  }
}
</style>
